﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Data.OleDb;
using System.Configuration;
using System.IO;
using System.Drawing.Drawing2D;
using System.Windows.Forms.DataVisualization.Charting;
using System.Timers;

namespace JQGJJ
{
    public partial class gzInput : Form
    {
        public string[] gzClassArray = new string[] { "载荷故障", "综合电子系统硬件故障", "应用软件故障", "继电器故障" };
        public string[] zhArray = new string[] { "噪声过大", "恒增益", "恒偏差", "卡死" };
        public string[] yyArray = new string[] { "CPU过载", "CPU故障" };
        public string[] clqccArray = new string[] { "处理器故障", "存储故障" };
        public string[] clqArray = new string[] { "处理器1的核1" , "处理器1的核2" , "处理器2的核1", "处理器2的核2" };
        public string[] ccArray = new string[] { "内存不够用" };
        public string[] yyrjgzArray= new string[] { "异常中断" , "超时（无响应）" };
        public System.Timers.Timer t;
        public DataTable currentCsvData;
        public List<double> currentGzData;
        public List<string> currentGzDataString;
        public int currentIndex = 0;
        Queue<double> Q1 = new Queue<double>();
        Queue<string> Q2 = new Queue<string>();
        int drawInterVal = 0;
        Random r = new Random();
        Object lock_ = new Object();
        public SerialPortSetDlg dlg = null;
        private bool stopState = false;
        private string tempQ2Value = string.Empty;
        private string tblogbak = string.Empty;
        public gzInput()
        {
            InitializeComponent();
        }

        public void timeout(object source, System.Timers.ElapsedEventArgs e)
        {

        }

        private void gzInput_Load(object sender, EventArgs e)
        {
            initUI();
            t = new System.Timers.Timer(1);
            t.Elapsed += new System.Timers.ElapsedEventHandler(timeout);
            t.AutoReset = true;
            string[] a = new string[] { };
            drawLineArea(a);
        }

        public void initDisplayData(string[] array, System.Windows.Forms.ComboBox control_object)
        {
            List<ListItem> combox_drop_list = new List<ListItem>();
            for(int i = 0; i< array.Length; i++)
            {
                ListItem item = new ListItem(i.ToString(), array[i]);
                combox_drop_list.Add(item);
            }
            control_object.DataSource = combox_drop_list;
            control_object.DisplayMember = "DATA";
            control_object.ValueMember = "ID";
        }

        public void initUI()
        {
            initDisplayData(gzClassArray, this.combox_class);
        }

        public void changedUpdateData()
        {
            //initDisplayData(yyArray, this.combox_yy);
            //initDisplayData(clqArray, this.combox_clq);
           // initDisplayData(zhdzArray, this.combox_zhdz);
        }

        private void combox_class_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = this.combox_class.SelectedIndex;
            switch(selectedIndex.ToString())
            {
                case "0":
                    initDisplayData(zhArray, this.combox_gz);
                    this.combobox_sub_gz.Visible = false;
                    this.combox_sub_gz2.Visible = false;
                    this.chart1.Parent = this.proGroup;
                    this.chart1.Dock = DockStyle.Fill;
                    this.chart1.Visible = true;
                    this.textBox1.Visible = false;
                    this.textBox1.Parent = null;
                    this.btnReadLog.Enabled = true;
                    this.tbLog.Text = tblogbak;
                    break;
                case "1":
                    initDisplayData(clqccArray, this.combox_gz);
                    this.chart1.Visible = false;
                    this.chart1.Parent = null;
                    this.textBox1.Visible = true;
                    this.textBox1.Parent = this.proGroup;
                    this.textBox1.Dock = DockStyle.Fill;
                    this.btnReadLog.Enabled = false;
                    this.tbLog.Text = "";
                    break;
                case "2":
                    this.combobox_sub_gz.Visible = false;
                    this.combox_sub_gz2.Visible = false;
                    initDisplayData(yyrjgzArray, this.combox_gz);
                    this.chart1.Visible = false;
                    this.chart1.Parent = null;
                    this.textBox1.Visible = true;
                    this.textBox1.Parent = this.proGroup;
                    this.textBox1.Dock = DockStyle.Fill;
                    this.btnReadLog.Enabled = false;
                    this.tbLog.Text = "";
                    break;
                default:
                    break;
            }
        }

        private void combox_gz_SelectedValueChanged(object sender, EventArgs e)
        {
            ListItem currentText = (ListItem)this.combox_gz.SelectedItem;
            if (string.Compare(currentText.DATA,"处理器故障")== 0)
            {
                this.combox_sub_gz2.Visible = true;
                this.combobox_sub_gz.Visible = true;
                initDisplayData(clqArray, this.combobox_sub_gz);
                initDisplayData(yyArray, this.combox_sub_gz2);
            }
            else if (string.Compare(currentText.DATA, "存储故障") ==0)
            {
                this.combox_sub_gz2.Visible = false;
                initDisplayData(ccArray, this.combobox_sub_gz);
            }
            else
            {
                this.combox_sub_gz2.Visible = false;
                this.combobox_sub_gz.Visible = false;
            }
        }

        private void btn_start_zh_Click(object sender, EventArgs e)
        {
            stopState = false;
            int selectedIndex = this.combox_class.SelectedIndex;
            if (selectedIndex == 0)
            {
                if (!readOriginData(this.tbLog.Text) || currentCsvData == null)
                {
                    return;
                }
            }
            tempQ2Value = string.Empty;
            Q1.Clear();
            Q2.Clear();
            textBox1.Enabled = false;
            timer1.Enabled = true;
            ListItem classItem = (ListItem)this.combox_class.SelectedItem;
            ListItem gzItem = (ListItem)this.combox_gz.SelectedItem;
            if (string.Compare(classItem.DATA, "载荷故障") == 0)
            {
                textBox1.Enabled = false;
                this.textBox1.Visible = false;
                if (string.Compare(gzItem.DATA, "噪声过大") == 0)
                {
                    currentGzData = Algorithm.ksj_zsgd(1.0, currentCsvData);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzData.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzData[i].ToString());
                        }
                        lock (lock_)
                        {
                            Q1.Enqueue(currentGzData[i]);
                        }

                    }
                }
                else if (string.Compare(gzItem.DATA, "恒增益") == 0)
                {
                    currentGzData = Algorithm.ksj_hzy(1.0, currentCsvData);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzData.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzData[i].ToString());
                        }
                        lock (lock_)
                        {
                            Q1.Enqueue(currentGzData[i]);
                        }

                    }
                }
                else if (string.Compare(gzItem.DATA, "恒偏差") == 0)
                {
                    currentGzData = Algorithm.ksj_hpc(1.0, currentCsvData);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzData.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzData[i].ToString());
                        }
                        lock (lock_)
                        {
                            Q1.Enqueue(currentGzData[i]);
                        }

                    }
                }
                else if (string.Compare(gzItem.DATA, "卡死") == 0)
                {
                    currentGzData = Algorithm.ksj_ks(1.0, currentCsvData);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzData.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzData[i].ToString());
                        }
                        lock (lock_)
                        {
                            Q1.Enqueue(currentGzData[i]);
                        }

                    }
                }
                else
                {

                }
            }
            else if (string.Compare(classItem.DATA, "综合电子系统硬件故障") == 0)
            {
                textBox1.Enabled = true;
                this.textBox1.Visible = true;
                if (string.Compare(gzItem.DATA, "处理器故障") == 0)
                {
                    ListItem gz_subItem = (ListItem)this.combobox_sub_gz.SelectedItem;
                    ListItem gz_subItem2 = (ListItem)this.combox_sub_gz2.SelectedItem;
                    if (string.Compare(gz_subItem.DATA, "处理器1的核1") == 0)
                    {
                        if (string.Compare(gz_subItem2.DATA, "CPU过载") == 0)
                        {
                            currentGzDataString = Algorithm.other(1);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }


                            }
                        }
                        else if (string.Compare(gz_subItem2.DATA, "CPU故障") == 0)
                        {
                            currentGzDataString = Algorithm.other(2);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                            
                        }
                        else
                        {

                        }
                    }
                    else if (string.Compare(gz_subItem.DATA, "处理器1的核2") == 0)
                    {
                        if (string.Compare(gz_subItem2.DATA, "CPU过载") == 0)
                        {
                            currentGzDataString = Algorithm.other(3);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                        }
                        else if (string.Compare(gz_subItem2.DATA, "CPU故障") == 0)
                        {
                            currentGzDataString = Algorithm.other(4);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                        }
                        else
                        {

                        }
                    }
                    else if (string.Compare(gz_subItem.DATA, "处理器2的核1") == 0)
                    {
                        if (string.Compare(gz_subItem2.DATA, "CPU过载") == 0)
                        {
                            currentGzDataString = Algorithm.other(5);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                        }
                        else if (string.Compare(gz_subItem2.DATA, "CPU故障") == 0)
                        {
                            currentGzDataString = Algorithm.other(6);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                        }
                        else
                        {

                        }
                    }
                    else if (string.Compare(gz_subItem.DATA, "处理器2的核2") == 0)
                    {
                        if (string.Compare(gz_subItem2.DATA, "CPU过载") == 0)
                        {
                            currentGzDataString = Algorithm.other(7);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                        }
                        else if (string.Compare(gz_subItem2.DATA, "CPU故障") == 0)
                        {
                            currentGzDataString = Algorithm.other(8);
                            SendData.StopWrite();
                            SendData.StartWrite();
                            for (int i = 0; i < currentGzDataString.Count; i++)
                            {
                                if (stopState)
                                    return;

                                if (dlg != null)
                                {
                                    SendData.WriteData(currentGzDataString[i]);
                                }
                                lock (lock_)
                                {
                                    Q2.Enqueue(currentGzDataString[i]);
                                }

                            }
                        }
                        else
                        {

                        }
                    }
                    else
                    {

                    }
                }
                else if (string.Compare(gzItem.DATA, "存储故障") == 0)
                {
                    ListItem gz_subItem = (ListItem)this.combobox_sub_gz.SelectedItem;
                    if (string.Compare(gz_subItem.DATA, "内存故障") == 0)
                    {
                        currentGzDataString = Algorithm.other(9);
                        SendData.StopWrite();
                        SendData.StartWrite();
                        for (int i = 0; i < currentGzDataString.Count; i++)
                        {
                            if (stopState)
                                return;

                            if (dlg != null)
                            {
                                SendData.WriteData(currentGzDataString[i]);
                            }
                            lock (lock_)
                            {
                                Q2.Enqueue(currentGzDataString[i]);
                            }

                        }
                    }
                    else
                    {

                    }
                }
                else
                {

                }
            }
            if (string.Compare(classItem.DATA, "应用软件故障") == 0)
            {
                textBox1.Enabled = true;
                this.textBox1.Visible = true;
                if (string.Compare(gzItem.DATA, "异常中断") == 0)
                {
                    currentGzDataString = Algorithm.other(10);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzDataString.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzDataString[i]);
                        }
                        lock (lock_)
                        {
                            Q2.Enqueue(currentGzDataString[i]);
                        }

                    }
                }
                else if (string.Compare(gzItem.DATA, "超时（无响应）") == 0)
                {
                    currentGzDataString = Algorithm.other(11);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzDataString.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzDataString[i]);
                        }
                        lock (lock_)
                        {
                            Q2.Enqueue(currentGzDataString[i]);
                        }

                    }
                }
                else
                {

                }
            }
            else if (string.Compare(classItem.DATA, "继电器故障") == 0)
            {
                textBox1.Enabled = true;
                this.textBox1.Visible = true;
                if (string.Compare(gzItem.DATA, "异常中断") == 0)
                {
                    currentGzDataString = Algorithm.other(12);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzDataString.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzDataString[i]);
                        }
                        lock (lock_)
                        {
                            Q2.Enqueue(currentGzDataString[i]);
                        }

                    }
                }
                else if (string.Compare(gzItem.DATA, "超时（无响应）") == 0)
                {
                    currentGzDataString = Algorithm.other(13);
                    SendData.StopWrite();
                    SendData.StartWrite();
                    for (int i = 0; i < currentGzDataString.Count; i++)
                    {
                        if (stopState)
                            return;

                        if (dlg != null)
                        {
                            SendData.WriteData(currentGzDataString[i]);
                        }
                        lock (lock_)
                        {
                            Q2.Enqueue(currentGzDataString[i]);
                        }

                    }
                }
                else
                {

                }
            }
        }

        private void drawLineArea(string name, List<string[]> list)
        {
            this.chart1.ChartAreas.Clear();
            this.chart1.Titles.Clear();
            this.chart1.Series.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                string areaName = string.Format("name_{0}", i);
                ChartArea chartarea = new ChartArea(areaName);
                this.chart1.ChartAreas.Add(chartarea);
                chartarea.AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
                chartarea.AxisY.MajorGrid.LineColor = System.Drawing.Color.Black;
                chartarea.AxisX.ScrollBar.Enabled = false;
                chartarea.AxisX.Minimum = 0;
                chartarea.AxisX.Maximum = 2000;
                chartarea.AxisX.Interval = 200;
                chartarea.AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
                chartarea.AxisY.MajorGrid.LineColor = System.Drawing.Color.Black;
                chartarea.AxisX.Title = "间隔";
                chartarea.AxisY.Title = "取值";
                chartarea.CursorX.Interval = 0D;
                chartarea.CursorX.IntervalOffsetType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Minutes;
                chartarea.CursorX.IsUserEnabled = true;
                chartarea.CursorX.IsUserSelectionEnabled = true;
                chartarea.AxisX.ScaleView.Zoomable = true;


                /*this.chart1.Titles.Add("距离监测");
                this.chart1.Titles[0].Text = "距离监测";
                this.chart1.Titles[0].ForeColor = Color.Red;
                this.chart1.Titles[0].Font = new System.Drawing.Font("Microsoft Sans serif", 12f);*/

                //定义存储和显示点的容器
                string seriesName = string.Format("seriesName_{0}", i);
                Series series = new Series(seriesName);
                series.ChartType = SeriesChartType.Spline;
                series.ChartArea = areaName;
                series.Color = Color.Yellow;
                series.MarkerBorderWidth = 2;
                series.MarkerSize = 4;
                series.MarkerStyle = MarkerStyle.Diamond;
                series.ToolTip = "距离" + "#VAL \r\n #AXISLABEL";
                chart1.Series.Add(series);

                for (int j = 0; j < list[i].Length; j++)
                {
                    series.Points.AddXY(j + 1, Convert.ToDouble(list[i][j]));
                    series.Points[j].ToolTip = "(#VALX,#VALY)";
                }
            }
        }

        private void drawLineArea(string[] data)
        {
            this.chart1.ChartAreas.Clear();
            ChartArea chartarea = new ChartArea("注入波形");
            this.chart1.ChartAreas.Add(chartarea);
            chartarea.AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
            chartarea.AxisY.MajorGrid.LineColor = System.Drawing.Color.Black;
            //chartarea.AxisX.ScrollBar.Enabled = false;
            chartarea.AxisX.Minimum = 0;
            chartarea.AxisX.Maximum = 2000;
            chartarea.AxisX.Interval = 200;
            chartarea.AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
            chartarea.AxisY.MajorGrid.LineColor = System.Drawing.Color.Black;
            chartarea.AxisX.Title = "间隔";
            chartarea.AxisY.Title = "取值";
            chartarea.CursorX.Interval = 0D;
            chartarea.CursorX.IntervalOffsetType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Minutes;
            chartarea.CursorX.IsUserEnabled = true;
            chartarea.CursorX.IsUserSelectionEnabled = true;
            chartarea.AxisX.ScaleView.Zoomable = true;
            chartarea.AxisX.ScrollBar.IsPositionedInside = true;
            chartarea.AxisX.ScrollBar.Size = 10;
            chartarea.AxisX.ScaleView.SmallScrollMinSize = 2;
            chartarea.AxisX.ScaleView.SmallScrollSize = double.NaN;

            this.chart1.Titles.Clear();
            this.chart1.Titles.Add("注入波形");
            this.chart1.Titles[0].Text = "注入波形";
            this.chart1.Titles[0].ForeColor = Color.Red;
            this.chart1.Titles[0].Font = new System.Drawing.Font("Microsoft Sans serif", 12f);

            //定义存储和显示点的容器
            this.chart1.Series.Clear();
            Series series = new Series("波形");
            series.ChartType = SeriesChartType.Spline;
            series.ChartArea = "注入波形";
            series.Color = Color.Red;
            series.MarkerBorderWidth = 2;
            series.MarkerSize = 4;
            series.MarkerStyle = MarkerStyle.Diamond;
            series.ToolTip = "波形" + "#VAL \r\n #AXISLABEL";
            chart1.Series.Add(series);

            for (int i = 0; i < data.Length; i++)
            {
                series.Points.AddXY(i + 1, Convert.ToDouble(data[i]));
                series.Points[i].ToolTip = "(#VALX,#VALY)";
            }
        }

        private void btn_end_zh_Click(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            this.chart1.Series[0].Points.Clear();
            Q1.Clear();
            Q2.Clear();
            drawInterVal = 0;
            if (dlg != null)
            {
                SendData.StopWrite();
                SendData.ClearQueue();
            }
            stopState = true;
            tempQ2Value = string.Empty;

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //this.chart1.Series[0].Points.Clear();
            lock (lock_)
            {
                if (Q1.Count > 0)
                {
                    if (drawInterVal >= Q1.Count)
                    {
                        this.timer1.Enabled = false;
                        this.textBox1.Enabled = false ;
                        drawInterVal = 0;
                        return;
                    }

                    chart1.Series[0].Points.AddY(Q1.ElementAt(drawInterVal));
                    Q1.Dequeue();
                    drawInterVal += 1;
                }
                else
                {
                    if (drawInterVal >= Q2.Count)
                    {
                        this.timer1.Enabled = false;
                        this.textBox1.Enabled = true;
                        return;
                    }
                    string displayValue = Q2.ElementAt(drawInterVal);
                    drawInterVal += 1;
                    tempQ2Value += displayValue + " ";
                    this.textBox1.Text = tempQ2Value;
                    Q2.Dequeue();

                }



            }

        }
        
        private void btnReadLog_Click(object sender, EventArgs e)
        {
            OpenFileDialog opd = new OpenFileDialog();
            opd.Filter = "数据文件(*.csv)|*.csv";
            opd.ValidateNames = true;
            opd.CheckPathExists = true;
            opd.CheckFileExists = true;
            if (opd.ShowDialog() == DialogResult.OK)
            {
                this.tbLog.Text = opd.FileName;
                tblogbak = this.tbLog.Text;
            }
        }

        private bool readOriginData(string fileName)
        {
            if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
            {
                return false;
            }
            else
            {
                currentCsvData = csvHelper.OpenCSV(fileName);
            }

            return true;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dlg == null)
            {
                dlg = new SerialPortSetDlg();
                dlg.StartPosition = FormStartPosition.CenterParent;
                dlg.ShowDialog();
            }
            else
            {
                dlg.StartPosition = FormStartPosition.CenterParent;
                dlg.ShowDialog();
            }
        }

        private void chart1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
        } 
        
    }
}
